const http = (opt) => {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        xhr.open(opt.method || 'GET', opt.url, true);
        
        const headers = Object.assign(
            {
                'Content-Type': 'application/x-www-form-urlencoded'
            }, opt.headers
        );
        
        for (let key in headers) {
            xhr.setRequestHeader(key, headers[key]);
        }
        
        // xhr.onreadystatechange = () => {
        //     if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
        //         console.log(xhr.responseText);
        //     }
        // };
        xhr.onload = () => {
            const response = parseData(xhr);
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(response);
            } else {
                reject(response);
            }
        };
        xhr.onerror = () => {
            reject(parseData(xhr));
        };
        xhr.send(generateData(opt.data));
    });
};

const generateData = (data) => {
    return Object.keys(data).map(key => {
        return encodeURIComponent(key) + '=' + encodeURIComponent(data[key]);
    }).join('&');
};


const parseData = (xhr) => {
    try {
        return {
            ...xhr,
            data: JSON.parse(xhr.response)
        };
    } catch (e) {
        return xhr;
    }
};

export default {
    get: (url, data) => http({method: 'GET', url, data}),
    post: (url, data) => http({method: 'POST', url, data}),
};